package util;

import javax.sound.sampled.*;
import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class PlayMusics extends Thread{
    @Override
    public void run() {
//        try {
//            URL cb;
//            File f = new File("D:\\FFOutput\\Ari Pulkkinen - Trine Main Theme.wav"); // 引号里面的是音乐文件所在的路径
////            File f = new File("D:\\FFOutput\\1.wav");
//            cb = f.toURL();
//            AudioClip aau;
//            aau = Applet.newAudioClip(cb);
//
//            aau.play();
//            aau.loop();//循环播放
//            System.out.println("可以播放");
//            //单曲 aau.stop()停止播放
//
//        } catch (MalformedURLException e) {
//
//            e.printStackTrace();
//        }

    try {
        AudioInputStream ais = AudioSystem.getAudioInputStream(new File("Ari Pulkkinen - Trine Main Theme.wav")); // 绝对路径
        AudioFormat aif = ais.getFormat();
        final SourceDataLine sdl;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);
        sdl = (SourceDataLine) AudioSystem.getLine(info);
        sdl.open(aif);
        sdl.start();
        FloatControl fc = (FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);
        // value可以用来设置音量，从0-2.0
        double value = 2;
        float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
        fc.setValue(dB);
        int nByte = 0;
        final int SIZE = 1024 * 64;
        byte[] buffer = new byte[SIZE];
        while (nByte != -1) {
            nByte = ais.read(buffer, 0, SIZE);
            sdl.write(buffer, 0, nByte);
        }
        sdl.stop();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}
